import { input, select } from '@inquirer/prompts'
import { clone } from 'src/utils/clone'
import path from 'path'
import fs from 'fs-extra'
import axios from 'axios'
import { name, version } from '../../package.json'
import { gt } from 'lodash'
import chalk from 'chalk'
import { log } from 'src/utils/log'

const figlet = require('figlet')

export interface TemplateInfo {
    name: string, // 模板名称 
    downloadUrl: string, // 模板下载地址
    description: string, // 模板描述
    branch: string, // 模板分支
}

export const templates: Map<string, TemplateInfo> = new Map([
    ['Vite-Vue3-Typescript11', {
        name: 'Vite-Vue3-Typescript-template',
        downloadUrl: 'git@gitee.com:uniqueU/admin-proStar.git',
        description: 'Vue3技术栈开发模板',
        branch: 'master'
    }],
    ['Vite-Vue3-Typescript10', {
        name: 'Vite-Vue3-Typescript-template',
        downloadUrl: 'git@gitee.com:uniqueU/admin-proStar.git',
        description: 'Vue3技术栈开发模板',
        branch: 'master'
    }]
])

const isOverwrite = async (fileName: string) => {
    log.warn(`${fileName}文件夹存在！`)
    return await select({
        message: '是否覆盖',
        choices: [
            {
                name: '覆盖',
                value: true
            },
            {
                name: '不覆盖',
                value: false
            }
        ]
    })
}

const figletText = async () => {
    const text = await figlet('hcreate-cli')
    log.info(chalk.green(text))
}

export const checkNpmVersion = async (name:string, version:string) => {
    const data = await axios.get(`https://registry.npmjs.org/${name}`)
    const latestVersion = data.data['dist-tags'].latest
    const needUpdate = gt(latestVersion, version)
    if (needUpdate) {
        log.warn(`当前版本:${chalk.blackBright(version)}不是最新版本，请更新版本,最新版本:${chalk.blackBright(latestVersion)}`)  
        log.info(`可使用: ${chalk.yellow('npm install hcreate-cli@latest')}或使用 ${chalk.yellow('hcreate-cli update')}更新`)
    }
    return needUpdate
}
export async function create(projectName?: string) {
    // 初始化模板列表
    const templateList = Array.from(templates).map((item: [string, TemplateInfo]) => {
        const [name, info] = item
        return {
            name,
            value: name,
            description: info.description,
        }
    })

    //  @inquirer/prompts 插件支持命令行交互
    if (!projectName) {
        projectName = await input({
            message: '请输入项目名称',
            default: 'my-project',
            validate: (input) => {
                if (!input) {
                    return '项目名称不能为空'
                }
                return true
            }

        })
    }

    // 如果文件夹存在，则提示用户是否覆盖
    const filePath = path.resolve(process.cwd(), projectName)
    if (fs.existsSync(filePath)) {
        const run = await isOverwrite(projectName)
        if (run) {
            fs.removeSync(filePath)
        } else {
            return
        }
    }

    const needUpdate = await checkNpmVersion(name, version)
    if (needUpdate) {
        log.warn('当前版本不是最新版本，请更新版本')
        return
    }

    const templateName = await select({
        message: '请选择模板',
        choices: templateList
    })

    const info = templates.get(templateName);

    if (info) {
        clone(info.downloadUrl, projectName, ['-b', info.branch])
    }

    figletText()

    // 通过 simple-git库 拉取github中模板
}